package com.example.springbootmybatis.service.impl;

import com.example.springbootmybatis.dao.AreaDao;
import com.example.springbootmybatis.entity.Area;
import com.example.springbootmybatis.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class AreaServiceImpl implements AreaService {

    @Autowired
    private AreaDao areaDao;

    public List<Area> findall(){
        return areaDao.select();
    }
    public Area findById(Integer id){
        return areaDao.selectById(id);
    }
    @Transactional
    public boolean save(Area o){
        if (!StringUtils.isEmpty(o.getAreaName())) {
            o.setCreateTime(new Date());
            try {
                int effectedNum = areaDao.insert(o);
                if (effectedNum > 0) {
                    return true;
                } else {
                    throw new  RuntimeException("入库失败！");
                }
            } catch (Exception e) {
                throw new  RuntimeException("入库失败！"+e.getMessage());
            }
        } else {
            throw new  RuntimeException("区域信息不能为空！");
        }
    }
    public boolean edit(Area o){
        if (!StringUtils.isEmpty(o.getAreaId())) {
            o.setLastEditTime(new Date());
            try {
                int effectedNum = areaDao.update(o);
                if (effectedNum > 0) {
                    return true;
                } else {
                    throw new  RuntimeException("修改失败！");
                }
            } catch (Exception e) {
                throw new  RuntimeException("修改失败！"+e.getMessage());
            }
        } else {
            throw new  RuntimeException("id不能为空！");
        }
    }
    public boolean del(Integer id){
        if (!StringUtils.isEmpty(id)) {
            try {
                int effectedNum = areaDao.delete(id);
                if (effectedNum > 0) {
                    return true;
                } else {
                    throw new  RuntimeException("删除失败！");
                }
            } catch (Exception e) {
                throw new  RuntimeException("删除失败！"+e.getMessage());
            }
        } else {
            throw new  RuntimeException("id不能为空！");
        }
    }
}
